package com.gxa.modules.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.gxa.modules.dto.WeatherDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;

//获取天气实例
@Component
public class Weather {
   WeatherDTO weatherDTO;
public  WeatherDTO getWeather(String address){
        String weather="";
    try {
       Integer id=Integer.parseInt(address);
        // 这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
        JSONObject resultJson = readJsonFromUrl("https://api.map.baidu.com/weather/v1/?district_id="+id+"&data_type=all&ak=ZDyFcPT2afm9LoBFQ0KaHA5GkFjQO3XT");
        System.out.println(resultJson);
        //resultJson 是返回结果，当前只取位置信息
        weather = ((JSONObject) resultJson.get("result")).getString("now");
         weatherDTO = JSON.parseObject(weather, WeatherDTO.class);


    } catch (Exception e) {
        e.printStackTrace();
    }
    return weatherDTO;
}

    /**
     * 读取
     *
     * @param rd
     * @return
     * @throws IOException
     */
    private static String readAll(BufferedReader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    /**
     * 创建链接
     *
     * @param url
     * @return
     * @throws IOException
     * @throws JSONException
     */
    private static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = JSONObject.parseObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }
}
